package com.itianyu.blog.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.itianyu.blog.dao.beans.Entry;
import com.itianyu.blog.dao.beans.RelUserRole;
import com.itianyu.blog.dao.beans.Tag;
import com.itianyu.blog.dao.beans.User;
import com.itianyu.blog.dao.interfaces.TagInterface;
import com.itianyu.blog.dao.interfaces.UserInterface;

/**
 * 标签控制层
 * @author wumgji
 */
@Controller
@RequestMapping("/userInfo")
public class UserInfoController {

	@Autowired
	private TagInterface tagInterface;

	@Autowired
	private UserInterface userInterface;

	// 调到注册界面
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView register() throws Exception {
		ModelMap model = new ModelMap();
		model.addAttribute("", "");
		return new ModelAndView("register", model);
	}
	
	// 显示文章列表
	@RequestMapping(value = "/userlist", method = RequestMethod.GET)
	public ModelAndView entrymanagelist() throws Exception {
		return new ModelAndView("userlist", new ModelMap().addAttribute("users", userInterface.findUserEntities()));
	}
	
	// 注册账号
		@RequestMapping(value = "/register1", method = RequestMethod.POST)
		public ModelAndView register1(User user) throws Exception {
			ModelMap model = new ModelMap();
			
			if(user.getUsername()==null||user.getUsername().equals("")){
				model.addAttribute("status", "用户名不能为空");
				return new ModelAndView("register", model);
			}
			
			if(user.getPassword()==null||user.getPassword().equals("")){
				model.addAttribute("status", "密码不能为空");
				return new ModelAndView("register", model);
			}
			
			User userOld=userInterface.findUserByName(user.getUsername());
			if(userOld!=null){
				model.addAttribute("status", "已经存在该账号");
				return new ModelAndView("register", model);
			}
			
			
			
			ShaPasswordEncoder sha = new ShaPasswordEncoder();
			sha.setEncodeHashAsBase64(false);
			String pwd = sha.encodePassword(user.getPassword(), null);
			user.setPassword(pwd);
			user.setCreationDate(new Date());
			user.setEnabled(true);
			userInterface.saveUser(user);
			model.addAttribute("", "");
			return new ModelAndView("loginform", model);
		}
		

	// 显示已发布博文总数以及对应的标签
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	@ResponseBody
	public List<Object[]> tagEntryCount() throws Exception {
		return tagInterface.findTagEntitiesAndEntryCount();
	}

	// 保存标签信息（tagId参数作用仅是保持url一致性）
	@RequestMapping(value = "/save", method = RequestMethod.GET, params = { "tagId", "tagname" })
	@ResponseBody
	public List<Object> saveTag(@RequestParam("tagId") int tagId, @RequestParam("tagname") String tagname) throws Exception {
		Tag tag = null;

		ArrayList<Object> list = new ArrayList<Object>();
		String decodeTagName = new String(tagname.getBytes("ISO-8859-1"), "UTF-8");

		if (tagId >= 0) {
			tag = tagInterface.findTag(tagId);
			if (tag != null) {
				tag.setTagname(decodeTagName);
				tag.setModificationDate(new Date());
			} else {
				list.add("Save failed... Can not find Tag with tagId <" + decodeTagName + ">.");
				return list;
			}
		} else {
			tag = tagInterface.createTag();
			tag.setTagname(decodeTagName);
			tag.setCreationDate(new Date());
			tag.setModificationDate(new Date());
		}

		tag = tagInterface.saveTag(tag);

		list.add("Tag <" + tag.getTagname() + "> successfully saved.");
		return list;
	}

	// 根据标签ID删除标签信息
	@RequestMapping(value = "/delete", method = RequestMethod.GET, params = { "tagId" })
	@ResponseBody
	public List<Object> deleteTag(@RequestParam("tagId") int tagId) throws Exception {
		tagInterface.deleteTag(tagId);

		ArrayList<Object> list = new ArrayList<Object>();
		list.add("成功删除标签");
		return list;
	}

}
